import { useState, useEffect } from 'react';
import { usePortfolio } from '../context/PortfolioContext';

const CourseForm = ({ isNew = false }) => {
  const { 
    isCourseModalOpen, 
    currentCourse, 
    closeCourseModal, 
    addCourse, 
    updateCourse
  } = usePortfolio();
  
  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    teacher: '',
    description: '',
    coverImage: ''
  });
  
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formError, setFormError] = useState('');

  // 当编辑模态框打开或currentCourse变化时，加载数据
  useEffect(() => {
    if (!isNew && currentCourse) {
      setFormData({
        name: currentCourse.name || '',
        teacher: currentCourse.teacher || '',
        description: currentCourse.description || '',
        coverImage: currentCourse.coverImage || ''
      });
    }
  }, [currentCourse, isNew]);

  // 处理表单输入变化
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setFormError('');
    
    try {
      if (isNew) {
        // 添加新课程
        await addCourse(formData);
        // 重置表单
        setFormData({
          name: '',
          teacher: '',
          description: '',
          coverImage: ''
        });
      } else {
        // 更新现有课程
        await updateCourse({ ...formData, id: currentCourse.id });
        closeCourseModal();
      }
    } catch (err) {
      setFormError(err.message || '操作失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 如果是编辑表单，只在模态框打开时显示
  if (!isNew && (!isCourseModalOpen || !currentCourse)) {
    return null;
  }

  return (
    <>
      {/* 编辑模态框的背景遮罩 */}
      {!isNew && isCourseModalOpen && (
        <div 
          className="fixed inset-0 bg-black/50 z-40"
          onClick={closeCourseModal}
        ></div>
      )}
      
      <div className={`bg-white dark:bg-gray-800 p-5 rounded-lg shadow-lg ${
        isNew 
          ? '' 
          : 'fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 max-w-lg max-h-[90vh] overflow-y-auto z-50 w-full max-w-lg'
      }`}>
        <h3 className="text-xl font-semibold mb-4">
          {isNew ? '添加新课程' : '编辑课程'}
        </h3>

        {formError && (
          <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
            <p className="text-red-600 dark:text-red-400 text-sm">{formError}</p>
          </div>
        )}
      
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block mb-1 text-sm font-medium">课程名称 *</label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleChange}
              required
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium">任课教师 *</label>
            <input
              type="text"
              name="teacher"
              value={formData.teacher}
              onChange={handleChange}
              required
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium">课程图片URL</label>
            <input
              type="url"
              name="coverImage"
              value={formData.coverImage}
              onChange={handleChange}
              placeholder="https://example.com/image.jpg"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium">课程简介</label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleChange}
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            ></textarea>
          </div>

          <div className="flex gap-3 justify-end pt-2">
            {!isNew && (
              <button
                type="button"
                onClick={closeCourseModal}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                取消
              </button>
            )}
            
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSubmitting ? (
                <span className="flex items-center gap-2">
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  {isNew ? '添加中...' : '保存中...'}
                </span>
              ) : (
                isNew ? '添加课程' : '保存修改'
              )}
            </button>
          </div>
        </form>
      </div>
    </>
  );
};

export default CourseForm;